import { Component, Prop, Vue } from 'vue-property-decorator'

@Component
export default class extends Vue {
  // ++++++++++ model ++++++++++
  // ++++++++++ props ++++++++++
  @Prop()
  url!: string

  // ++++++++++ data ++++++++++
  visible = false
  filename = ''

  // Vue Cropper
  img: string | null = null
  previews = {} as any

  // ++++++++++ computed ++++++++++
  // ++++++++++ methods normal ++++++++++
  realTime(data: any) {
    this.previews = data
  }

  // ++++++++++ methods event ++++++++++
  // 提交
  submit() {
    const cropper = this.$refs.cropper as any
    const _this = this

    cropper.getCropBlob(async (data: any) => {
      const form = new FormData()

      form.append('file', data, _this.filename)
      // const { filepath } = await this.$Api.file.upload(form)

      // this.$emit('update:url', filepath)

      this.$emit('update:url', URL.createObjectURL(data))
      this.visible = false
    })
  }

  // 上传文件改变
  handleOnChange(file: any) {
    const is5M = file.size / 1024 / 1024 < 5

    this.filename = file.name

    if (!is5M) {
      this.$message.warning('上传文件大小不能超过 5MB!')
      return false
    }

    this.$nextTick(() => {
      this.img = URL.createObjectURL(file.raw)
      this.visible = true
    })
  }

  // 放大
  handleScaleBig() {
    const cropper = this.$refs.cropper as any

    cropper.changeScale(0.5)
  }

  // 缩小
  handleScaleSmall() {
    const cropper = this.$refs.cropper as any

    cropper.changeScale(-0.5)
  }

  // 左旋转
  handleRotateLeft() {
    const cropper = this.$refs.cropper as any

    cropper.rotateLeft()
  }

  // 右旋转
  handleRotateRight() {
    const cropper = this.$refs.cropper as any

    cropper.rotateRight()
  }
  // ++++++++++ Lifecycle Hooks ++++++++++
  // ++++++++++ watch ++++++++++
}
